<template>
  <div class='home-container'>
    <van-nav-bar fixed title="黑马头条" />

    <!-- 导入注册使用ArticleInfo组件 -->
    <van-pull-refresh v-model="isLoading" :disabled='finished' @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <ArticleInfo v-for='item in artlist' :key='item.id' :title='item.title'
        :author='item.aut_name' :cmtCount='item.comm_count' :time='item.pubdate'
        :cover='item.cover'></ArticleInfo>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 导入request.js
import request from '@/utils/request.js'
import ArticleInfo from '@/components/Article/ArticleInfo.vue'

export default {
  name: 'Home',
  data () {
    return {
      page: 1,
      limit: 10,
      artlist: [],
      loading: true,
      finished: false,
      isLoading: false
    }
  },
  components: {
    ArticleInfo
  },
  created () {
    this.initArticleList()
  },
  methods: {
    async initArticleList (isRefresh) {
      const { data: res } = await request.get('/articles', {
        params: {
          _page: this.page,
          _limit: this.limit
        }
      })
      // this.artlist = [旧数据在前，新数据在后] 上拉加载更多
      if (isRefresh) {
        // 下拉刷新 新数据在前
        this.artlist = [...res, ...this.artlist]
        this.isLoading = false
      } else {
        this.artlist = [...this.artlist, ...res]
        this.loading = false
      }

      if (res.length === 0) {
        this.finished = true
      }
    },
    onLoad () {
      console.log('出发了load事件')
      // 让页码值+1
      // 重新请求接口获取数据
      this.page++
      this.initArticleList()
    },
    onRefresh () {
      console.log('下拉刷新')
      // 页码值+1
      // 重新请求接口数据
      this.page++
      this.initArticleList(true)
    }
  }
}
</script>

<style lang="less" scoped>
.home-container {
  padding: 46px 0 50px 0;

  // .van-nav-bar {
  //   background-color: #007bff;
  // }

  // /deep/ .van-nav-bar__title {
  //   color: #fff;
  // }
}
</style>
